package system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.*;

@WebServlet("/userInf")
public class userInf extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//super.service(request, response);
		String user_id=request.getParameter("user_id");
		String password = request.getParameter("password");
		String[] inf = getUserInf(user_id);
        String result = "{\"code\":"+getWhetherMatch(user_id, password)+",\"id\":\""+inf[0]+"\",\"pwd\":\""+inf[1]+"\",\"name\":\""+inf[2]+"\",\"email\":\""+inf[3]+"\",\"type\":\""+inf[4]+"\"}";
		
        if(getWhetherMatch(user_id, password)==1) {
        	HttpSession session=request.getSession();
        	Boolean state=new Boolean(true);
            session.setAttribute("state",state);
            session.setAttribute("userid",user_id);
        }
        
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();		
		out.write(result);

	}
	
	public int getWhetherMatch(String id,String pwd){
		String[] userInf=null;
		boolean whetherMatch;
		
		sqlOperation sql = new sqlOperation();
		
		userInf=sql.getQueryLine("SELECT * from user_inf where user_id="+"'"+id+"'",5);
	    if(pwd.equals(userInf[1].trim())){
	    	whetherMatch=true;
		}else whetherMatch=false;	
	    if(whetherMatch)
	    	return 1;
	    else return 0;
	}
	
	public String[] getUserInf(String id){
		String[] userInf=null;

		sqlOperation sql = new sqlOperation();
		
		userInf=sql.getQueryLine("SELECT * from user_inf where user_id="+"'"+id+"'",5);

	    return userInf;
	}
}
